<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addRold(1,'0')">添加权限</el-button>
        </div>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type===1" type="text" @click="addRold(2,scope.row.id)">添加</el-button>
              <el-button type="text" @click="editRold(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delRold(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 放置一个弹层 用来编辑新增节点 -->
      <el-dialog title="新增权限点" :visible="showDialog" @close="btnCancel">
        <!-- 表单 -->
        <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" style="width:90%" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" style="width:90%" />
          </el-form-item>
          <el-form-item label="权限描述">
            <el-input v-model="formData.description" style="width:90%" />
          </el-form-item>
          <el-form-item label="开启">
            <el-switch
              v-model="formData.enVisible"
              active-value="1"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" type="primary" @click="add">确定</el-button>
            <el-button size="small" @click="btnCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, getPermissionDetail, updatePermission, delPermission } from '@/api/permission'
import { transTree } from '@/utils' // 引入转换树形结构的方法
export default {
  name: 'Permission',
  data() {
    // 校验权限名称
    // 新增：只要同级的没有重名的就行
    // 新增：判断每一项的pid是否等于formData中的pid，如果一致就是同级
    const validName = (rules, value, callback) => {
      // 先选出所有同级的元素
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)
      // 如果是编辑里的，需要把自己剔除
      if (this.isEdit) {
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      existNameList.map(it => it.name).includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }
    // 验证权限标识
    const validCode = (rules, value, callback) => {
      let existCodeList = this.originList
      // 如果是编辑
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      existCodeList.map(item => item.code).includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }

    return {
      permissionList: [], // 权限管理列表数据
      showDialog: false, // 是否显示弹层
      isEdit: false, // 点击是否是编辑 true是编辑 false不是编辑
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],

        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      },
      originList: [] // 在做校验时需要用到的数据
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      // console.log(res)
      this.permissionList = transTree(res.data)
      // 为了添加自定义校验规则，改造一个简易数组
      this.originList = res.data.map(({ id, pid, name, code }) => {
        return { id, pid, name: name.trim(), code }
      })
      console.log(this.originList)
    },

    // 点击添加（权限）按钮
    addRold(type, pid) {
      this.showDialog = true
      this.isEdit = false// 点击的是添加不是编辑
      // console.log(type, pid)
      this.formData.type = type
      this.formData.pid = pid
    },

    // 点击编辑按钮
    async editRold(id) {
      this.isEdit = true // 点击的是编辑
      const res = await getPermissionDetail(id) // 数据回显
      this.formData = res.data // 把结果赋值给formData
      this.showDialog = true
    },
    // 添加时确认按钮单独封装
    async addPermission() {
      // this.isEdit = false
      const res = await addPermission(this.formData) // 调用添加权限按钮
      this.$message.success(res.message)
      this.showDialog = false
      this.getPermissionList()// 重新渲染页面
    },

    // 点击编辑的确认按钮
    async editPermission() {
      // this.isEdit = true
      const res = await updatePermission(this.formData)
      this.$message.success(res.message)
      this.showDialog = false
      this.getPermissionList()// 重新渲染页面
    },

    // 点击编辑或添加的确认按钮，根据判断点的是编辑还是添加做出反应
    add() {
      this.$refs.perForm.validate(async valid => {
        if (!valid) return
        this.isEdit ? this.editPermission() : this.addPermission()
      })
    },

    // 点击取消或者点击弹框的叉子
    btnCancel() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.perForm.resetFields()
      this.showDialog = false
      this.isEdit = false// 关闭后把编辑状态置为false
    },
    // 点击删除按钮
    async delRold(id) {
      const confirmRes = await this.$confirm('确定删除此项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmRes)
      if (confirmRes === 'cancel') return this.$message.info('您取消了删除')
      const res = await delPermission(id)
      this.$message.success(res.message)
      this.getPermissionList()
    }
  }
}
</script>

<style lang="scss" scoped></style>

